/**
 * Created by HYDN on 2020/6/19.
 */
const express=require('express');
const userService=require('../services/userService');

var router=express.Router();

router.post('/register',async (req,res,next)=> {
    var user=req.query;
    if(user==undefined||user=={}||user==[]){
        res.send({success:false,msg:'用户名密码不能为空'})
    }else {
        var data=userService.addUser(user);
        if(data.success){
            return {success:true,user:data.user};
        }else {
            return data;
        }
    }
});
router.post('/login',async (req,res,next)=>{
    var user=req.body;
    if(user==undefined||user=={}||user==[]){
        res.send({success:false,msg:'用户名密码不能为空'})
    }else {
        var data=await userService.login(user);
        //登录成功进行session与cookie
        if(data.success){
            //登录成功对cookie进行操作，同时也对session进行操作
            if(user.remember=='true'){
                res.cookie("user",data.user,{maxAge:7*27*60*60*1000});
            }
                //登录之后立即记录
                req.session.user=data.user;
        };
        res.send(data);
    }
});
//用户退出是清除session
router.use('/logout',(req,res)=>{
    var user=req.session['user'];
    if(user==null||user=={}||user==undefined){
        res.send('have not log in');
    }else {
        req.session.destroy();
        res.send('/views/index.html');
    }
});
exports.router=router;